
package managedbeans;


import entities.Authorisation;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import langresources.ResourcesController;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import utils.dataaccess.DBInterface;
import utils.dataaccess.IOUtil;
import utils.security.SHAHashUtil;



@ManagedBean(name = "userInfoBean")
@SessionScoped
public class UserInfoBean extends GenericForumBean{

    @EJB SHAHashUtil hasher;
    
    private String password;
    private String email;
    private String avatarPath;
    private int messagesCount = 0;
    private byte[] avatarBytes = null;
    
    public UserInfoBean() {
        
    }
    
    public void initUserParameters(Authorisation user){
        password = user.getPassword();
        email = user.getEmail();
        avatarPath = retrieveAvatarPath(user.getUsername());
        messagesCount = DBInterface.getPosts(user).size();
    }
    
    
    public void handleFileUpload(FileUploadEvent evt){
        UploadedFile uploadedFile = evt.getFile();
        avatarBytes = uploadedFile.getContents();
    }
    
    

    public void applyChanges(Authorisation user){
        user.setEmail(email);
        user.setPassword(password);
        DBInterface.persist(user);
        
        if(avatarBytes != null){
            IOUtil.updateAvatar(avatarBytes, user.getUsername());
        }
        showMessage(ResourcesController.extractResource("MESSAGE.INFO"), ResourcesController.extractResource("USERDATA_CHANGED"));
    }
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = hasher.getHash(password);
    }

    public int getMessagesCount() {
        return messagesCount;
    }

    public void setMessagesCount(int messagesCount) {
        this.messagesCount = messagesCount;
    }

    public String getAvatarPath() {
        return avatarPath;
    }

    public void setAvatarPath(String avatarPath) {
        this.avatarPath = avatarPath;
    }
    
}
